package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.TableUI;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.business.CustomUtil;
import com.taotao.wechat.game.ShareOneImage;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/playGame")
public class PlayGameController {
    private SimpleDateFormat shortDF = new SimpleDateFormat("yyyy-MM-dd");


    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object getListByPage(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Long pageSize = Long.parseLong(request.getParameter("pageSize"));
        Long pageNo = Long.parseLong(request.getParameter("pageNo"));

        String prize = request.getParameter("prize");

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");

        Date now = new Date();
        Long start;
        try {
            Date theStart = shortDF.parse(startDate);
            start = new DateTime(theStart.getTime()).getMillis();
        } catch (Exception e) {
            start = DateTimeUtil.getDateStartMillis(now);
        }
        Long end;
        try {
            Date theEnd = shortDF.parse(endDate);
            end = new DateTime(theEnd.getTime()).plusDays(1).minusMillis(1).getMillis();
        } catch (Exception e) {
            end = DateTimeUtil.getDateEndMillis(now);
        }

        PlayGame condition = new PlayGame();
        condition.setPageSize(pageSize);
        condition.setPageNo(pageNo);
        condition.setGameName(new ShareOneImage().getNickName());
        condition.setStartTime(start);
        condition.setEndTime(end);
        if (StringUtils.isNotBlank(prize)) {
            condition.setPrize(Integer.parseInt(prize));
        }

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.listByPage", "1.0");
        if (response.isSuccessful()){
            BaseResponse resp = response.getSuccessResponse();
            if (resp.getSuccess()){
                TableUI tableUI = new TableUI();
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) resp.getData();
                tableUI.setTotal(resp.getMsg());
                tableUI.setRows(respData);
                return tableUI;
            } else {
                return resp;
            }
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        PlayGame playGame = new PlayGame();
        playGame.setId(Long.parseLong(id));
        playGame.setPrize(-2);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(playGame, BaseResponse.class, "playGame.updateGamePrize", "1.0");
        if (response.isSuccessful()){
            return response.getSuccessResponse();
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    @RequestMapping(value = "/forceAudit/{id}", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public Object forceAudit(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        if (has200(request)) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.setSuccess(false);
            baseResponse.setMsg("已经审满200名，辛苦了~");
            return baseResponse;
        }

        request.setCharacterEncoding("UTF-8");
        PlayGame playGame = new PlayGame();
        playGame.setId(Long.parseLong(id));
        playGame.setPrize(1);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(playGame, BaseResponse.class, "playGame.updateGamePrize", "1.0");
        if (response.isSuccessful()){
            //自动删除此微信号、此手机号其他记录
            PlayGame condition = new PlayGame();
            condition.setId(Long.parseLong(id));
            CompositeResponse<BaseResponse> thePlayGame = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                    .post(condition, BaseResponse.class, "playGame.list", "1.0");
            if (thePlayGame.isSuccessful()) {
                BaseResponse theResp = thePlayGame.getSuccessResponse();
                if (theResp.getSuccess()) {
                    List<LinkedHashMap<String, Object>> theDate = (List<LinkedHashMap<String, Object>>) theResp.getData();
                    if (theDate != null && theDate.size() > 0) {
                        String appId = theDate.get(0).get("appId").toString();
                        String openId = theDate.get(0).get("openId").toString();
                        String gameName = theDate.get(0).get("gameName").toString();
                        String tel = theDate.get(0).get("tel").toString();

                        PlayGame wechatCondition = new PlayGame();
                        wechatCondition.setGameName(gameName);
                        wechatCondition.setAppId(appId);
                        wechatCondition.setOpenId(openId);
                        wechatCondition.setPrize(-1);
                        MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                                .post(wechatCondition, BaseResponse.class, "playGame.updateGamePrize", "1.0");

                        PlayGame telCondition = new PlayGame();
                        telCondition.setGameName(gameName);
                        telCondition.setTel(tel);
                        telCondition.setPrize(-1);
                        MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                                .post(telCondition, BaseResponse.class, "playGame.updateGamePrize", "1.0");
                    }
                } else {
                    return theResp;
                }
                return response.getSuccessResponse();
            } else  {
                return thePlayGame.getErrorResponse().getSubErrors().get(0);
            }
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    @RequestMapping(value = "/audit/{id}", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public Object audit(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        if (has200(request)) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.setSuccess(false);
            baseResponse.setMsg("已经审满200名，辛苦了~");
            return baseResponse;
        }

        request.setCharacterEncoding("UTF-8");
        PlayGame condition = new PlayGame();
        condition.setId(Long.parseLong(id));
        CompositeResponse<BaseResponse> thePlayGame = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (thePlayGame.isSuccessful()) {
            BaseResponse theResp = thePlayGame.getSuccessResponse();
            if (theResp.getSuccess()) {
                List<LinkedHashMap<String, Object>> theDate = (List<LinkedHashMap<String, Object>>) theResp.getData();
                if (theDate != null && theDate.size() > 0) {
                    String appId = theDate.get(0).get("appId").toString();
                    String openId = theDate.get(0).get("openId").toString();
                    //发送客服消息
                    String finishTime = DateTimeUtil.parseDate(Long.parseLong(theDate.get(0).get("finishTime").toString()));
                    String tel = theDate.get(0).get("tel").toString();
                    ShareOneImage shareOneImage = new ShareOneImage();
                    String customMsg = "";
                    int num = shareOneImage.getNumberOfAudited();
                    if (num != -1) {
                        String prizeStr = "500M流量";
                        if (num <= 99) {
                            prizeStr = "1G流量";
                        }
                        customMsg = "您的手机号码" + tel + "，在" + finishTime + "已经获得" + prizeStr + "，谢谢参与【" + shareOneImage.getName() +"】活动~";
                    }
                    if (StringUtils.isNotBlank(customMsg)
                            && CustomUtil.sendTextMesaage(appId, openId, customMsg)) {
                        return forceAudit(request, id);
                    } else {
                        BaseResponse baseResponse = new BaseResponse();
                        baseResponse.setSuccess(false);
                        baseResponse.setMsg("发送客服消息失败");
                        return baseResponse;
                    }
                } else {
                    BaseResponse baseResponse = new BaseResponse();
                    baseResponse.setSuccess(false);
                    baseResponse.setMsg("发送客服消息失败~");
                    return baseResponse;
                }
            } else {
                return theResp;
            }
        } else {
            return thePlayGame.getErrorResponse().getSubErrors().get(0);
        }
    }

    private boolean has200(HttpServletRequest request) {
        PlayGame condition = new PlayGame();
        condition.setPrize(1);
        condition.setGameName(new ShareOneImage().getNickName());
        String startDate = request.getParameter("startDate");
        Long start;
        try {
            Date theStart = shortDF.parse(startDate);
            start = new DateTime(theStart.getTime()).getMillis();
        } catch (Exception e) {
            start = DateTimeUtil.getDateStartMillis(new Date());
        }
        condition.setStartTime(DateTimeUtil.getDateStartMillis(new Date(start)));
        condition.setEndTime(DateTimeUtil.getDateEndMillis(new Date(start)));

        CompositeResponse<BaseResponse> thePlayGame = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (thePlayGame.isSuccessful()) {
            BaseResponse theResp = thePlayGame.getSuccessResponse();
            if (theResp.getSuccess()) {
                List<LinkedHashMap<String, Object>> theDate = (List<LinkedHashMap<String, Object>>) theResp.getData();
                if (theDate != null && theDate.size() >= 200) {
                    return true;
                }
            }
        }
        return false;
    }
}
